<template>
  <div class="prod-page">
    <div class="prod-nav">
      <van-nav-bar
        title="用户的商品橱窗"
      />
      <van-tabs v-model="state.navActive" color="#FE2E4E" @click="handleNav">
        <van-tab v-for="(item, index) in state.prodNav" :key="index" :name="item.id" :title="item.title"></van-tab>
      </van-tabs>
    </div>

    <van-list
      class="prod-list"
      v-model:loading="state.loading"
      :finished="state.finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <router-link v-for="(item, index) in state.list" :key="index" :to="{ name: 'prodDetail', query: { pdId: item.pdId } }">
        <van-card :thumb="item.imageUrl">
          <template #title><h2 class="van-multi-ellipsis--l2">{{item.title}}</h2></template>
          <template #price>
            <div class="prod-price">价格：<strong class="clr-red">￥{{item.price}}</strong></div>
          </template>
        </van-card>
      </router-link>
    </van-list>
  </div>
</template>

<script>
import { reactive, getCurrentInstance } from 'vue'
import {
  getUserProductCategoryList,
  getUserShopListByCategoryId
} from '@api'
export default {
  name: 'prodList',
  setup () {
    const { proxy } = getCurrentInstance()
    // console.log(proxy.$root.$route.query.sellerUserId)
    // console.log(proxy.$root.$router)

    const state = reactive({
      sellerUserId: proxy.$root.$route.query.sellerUserId,
      categoryId: '',
      pageNum: 0,
      prodNav: null,
      navActive: '',
      list: [],
      loading: false,
      finished: false
    })

    const onLoad = async () => {
      const { prodNav } = state

      // 获取分类
      if (!prodNav) {
        await getUserProductCategoryList(state.sellerUserId).then(res => {
          const { content } = res
          state.prodNav = content
          state.categoryId = content[0].id
        })
      }

      // 获取列表
      const { pageNum, categoryId, sellerUserId } = state
      getUserShopListByCategoryId({
        pageNum,
        categoryId,
        sellerUserId
      }).then(res => {
        const { content, pageNo, totalPages } = res.content
        console.log(content)
        state.list = state.list.concat(content)
        state.pageNum = pageNo
        // 加载状态结束
        state.loading = false
        // 数据全部加载完成
        if (pageNo + 1 >= totalPages) {
          state.finished = true
        }
      })
    }

    // 分类切换
    const handleNav = (name, title) => {
      console.log(name, title)
      state.categoryId = name
      state.pageNum = 0
      state.list = []
      state.finished = false
    }

    return {
      state,
      onLoad,
      handleNav
    }
  }
}
</script>

<style scoped lang="scss">
@import './prodList.scss';
</style>
